package com.gnerv.pabu.basic.core.service.impl;

import com.gnerv.pabu.basic.core.service.IFreemarkerService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Map;

@Slf4j
@Service
public class FreemarkerServiceImpl implements IFreemarkerService {

    @Autowired
    Configuration configuration;

    @Override
    public Template getTemplate(String path) {
        Template template = null;
        try {
            template = configuration.getTemplate("cms/index.ftl");
        } catch (IOException e) {
            log.info("获取模板异常", e);
        }
        return template;
    }

    @Override
    public String createContent(Template template, Map data) {
        try {
            String content = FreeMarkerTemplateUtils.processTemplateIntoString(template, null);
            return content;
        } catch (IOException e) {
            log.info("生成内容异常", e);
        } catch (TemplateException e) {
            log.info("生成内容异常", e);
        }
        return null;
    }

    @Override
    public boolean createHtml(String content, String path) {
        String resourcePath = ClassUtils.getDefaultClassLoader().getResource("").getPath();
        File file = new File(resourcePath + "/public");
        if(!file.exists()){
            file.mkdir();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(new File(file, "index.html"));
            FileCopyUtils.copy(content.getBytes(), fileOutputStream);
        } catch (FileNotFoundException e) {
            log.info("生成静态html异常", e);
        } catch (IOException e) {
            log.info("生成静态html异常", e);
        }
        return true;
    }
}
